<template>
  <common-page title="视频看板" :istabs="true" class="warn-page">
    <div class="video-tree-container">
      <div class="ship-tree-panel">
        <el-select class="company-selector" v-model="companyId" filterable placeholder="请选择" @change="companySelectChange">
          <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
        <el-tree
          ref="shipTree"
          :default-expanded-keys="shipTreeExpandKeys"
          :data="shipTreeData"
          :props="defaultTreeProps"
          node-key="id"
          @node-click="handleTreeNodeClick"
        >
          <span slot-scope="{ node }" class="treeIcon">
            <el-tooltip class="item" effect="dark" :content="node.label" placement="left-start">
              <span> {{ node.label }} </span>
            </el-tooltip>
            <div></div>
          </span>
        </el-tree>
      </div>
      <div class="video-container" :class="{ big: panelSize === 1 }">
        <div class="tools">
          分屏：
          <i class="el-icon-full-screen btn" :class="{ selected: gridNum == 1 }" @click="chageVideoNum(1)"></i>
          <i class="el-icon-menu btn btn" :class="{ selected: gridNum == 4 }" @click="chageVideoNum(4)"></i>
          <i class="el-icon-s-grid btn" :class="{ selected: gridNum == 9 }" @click="chageVideoNum(9)"></i>
          <div class="right-box">
            <span @click="changePanel(1)" v-if="panelSize === 0"><el-button size="small" type="primary">看板扩展</el-button></span>
            <span @click="changePanel(0)" v-if="panelSize === 1"><el-button size="small" type="primary">看板还原</el-button></span>
          </div>
        </div>
        <div
          v-if="videoList && videoList.length > 0"
          class="video-list"
          :class="gridNum == 1 ? 'video-list-grid1' : gridNum == 4 ? 'video-list-grid4' : gridNum == 9 ? 'video-list-grid9' : ''"
        >
          <div
            v-for="index in gridNum"
            :key="index"
            class="video-item"
            :class="{ selected: index - 1 == selectVideoIndex }"
            @click="selectVideoIndex = index - 1"
          >
            <div v-if="!(videoList && videoList[index - 1] && videoList[index - 1].id)" style="color: #ffffff; font-size: 30px; font-weight: bold">
              {{ index }}
            </div>
            <TheVideo v-else ref="player" :video="videoList[index - 1]"></TheVideo>
          </div>
        </div>
      </div>
    </div>
    <!-- <video ref="video" class="video" autoplay muted></video> -->
  </common-page>
</template>
<script>
import { VideoFlv } from '@haiking/haiking-jstool'
import dictUtil from '@/utils/dictUtils'
import { getDict } from '@/api/dict'
import VideoDialog from '@/components/video-dialog'
import TheVideo from '@/components/video/jessibuca'
import { createNamespacedHelpers } from 'vuex'
import { getNewTenantShipTree } from '@/api/ship'
import { getTenantBySupervise, keepRealtimeVideoStreamPatch } from '@/api/video'
const { mapState } = createNamespacedHelpers('user')
export default {
  name: 'VideoRealtime',
  components: {
    TheVideo
  },
  data() {
    return {
      searchParam: {
        shipId: '',
        installationPoint: undefined,
        status: undefined
      },
      companyList: [],
      companyId: undefined,
      gridNum: 1,
      selectVideoIndex: 0,

      defaultTreeProps: {
        children: 'children',
        label: 'name'
      },
      installationPointList: [],
      // value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
      value1: undefined,
      shipTreeData: [],
      shipTreeExpandKeys: [],
      currentShip: {},
      videoList: [{}],

      keepInterval: undefined,
      panelSize: 0
    }
  },
  computed: {
    ...mapState(['tenantId'])
  },
  mounted() {
    this.initData()
  },
  destroyed() {
    this.clearKeepInterval()
  },
  methods: {
    getQueryParams() {
      if (this.$route.query) {
        if (this.$route.query.shipId) {
          this.searchParam.shipId = this.$route.query.shipId
        }
      }
    },
    async initData() {
      // const installationPointResult = await getDict({code: "installation_point"})
      // if (installationPointResult.result && installationPointResult.result.length > 0) {
      //     this.installationPointList = installationPointResult.result
      // }
      const companyResult = await getTenantBySupervise(this.tenantId)
      if (companyResult.result && companyResult.result.length > 0) {
        this.companyList = companyResult.result
      }
      if (this.companyList && this.companyList.length > 0) {
        this.companyId = this.companyList[0].id
        this.switchVideoTree(this.companyId)
      }

      this.startKeepVideo()
    },
    companySelectChange(companyId) {
      this.switchVideoTree(companyId)
    },

    // 切换视频树结构
    async switchVideoTree(companyId) {
      const queryTennantResult = await getNewTenantShipTree(companyId)
      if (queryTennantResult.result && queryTennantResult.result.length > 0) {
        this.shipTreeData = queryTennantResult.result
        // if (this.$route.query && this.$route.query.shipId) {
        //   this.currentShip = this.shipTreeData.find(item => item.code == this.$route.query.shipId)
        // }
        // if (!this.currentShip.code) {
        //   this.currentShip = this.shipTreeData[0];
        // }
        this.currentShip = this.shipTreeData[0]
        this.shipTreeExpandKeys = [this.currentShip.code]

        this.searchParam.shipId = this.currentShip.code
        this.$nextTick(() => {
          // if (this.$route.query && this.$route.query.installationPoint) {
          //   this.searchParam.installationPoint = this.$route.query.installationPoint
          //   this.$refs.shipTree.setCurrentKey(this.searchParam.shipId + "_" + this.searchParam.installationPoint);
          // } else {
          //   this.$refs.shipTree.setCurrentKey(this.searchParam.shipId);
          // }
          this.$refs.shipTree.setCurrentKey(this.searchParam.shipId)
        })
      } else {
        this.shipTreeData = []
      }
    },
    chageVideoNum(num) {
      this.gridNum = num
      const videoNum = this.gridNum
      const videos = []
      for (let index = 0; index < videoNum; index++) {
        videos.push({})
      }
      this.videoList = videos
    },

    onShipChange(id) {
      if (this.shipTreeData && this.shipTreeData.length > 0) {
        const shipItem = this.shipTreeData.find((val) => val.id === id)
        if (shipItem) {
          this.currentShip = shipItem
        }
      }
    },
    // 清除心跳保活定时器
    clearKeepInterval() {
      if (this.keepInterval) {
        clearInterval(this.keepInterval)
      }
      this.keepInterval = undefined
    },
    // 开启心跳发送，保活
    startKeepVideo() {
      this.clearKeepInterval()
      const liveVideos = {}
      this.keepInterval = setInterval(() => {
        for (let index = 0; index < this.gridNum; index++) {
          const videoData = this.$refs.player && this.$refs.player[index] && this.$refs.player[index].getLiveVideo()

          if (videoData && videoData.id) {
            liveVideos[videoData.id] = videoData
          }
        }

        const liveVideoVals = Object.values(liveVideos)
        if (liveVideoVals && liveVideoVals.length > 0) {
          keepRealtimeVideoStreamPatch(
            liveVideoVals.map((val) => {
              return {
                cameraId: val.code,
                channelId: val.channelId,
                shipCatCode: val.shipcatCode
              }
            })
          )
        }

        // keepRealtimeVideoStream({
        //   cameraId: video.code,
        //   // clientType: 1,
        //   // platform: "sturgeon",
        //   // streamQuality: "01",
        //   channelId: video.channel,
        //   streamType: video.timeRange ? 2 : 1,// 历史流2，实时流1
        //   shipCatCode: video.shipcatCode,
        //   startTime: video.timeRange && video.timeRange[0],
        //   endTime: video.timeRange && video.timeRange[1]
        // })
      }, 60000)
    },
    handleTreeNodeClick(data, node) {
      // let shipId,installationPoint;
      // if (data.type === "installation_point") {
      //   installationPoint = data.code;
      //   this.currentShip = node.parent.data;
      //   shipId = this.currentShip.id;
      // } else if (data.type === "ship") {
      //   this.currentShip = data;
      //   shipId = data.code;
      // }
      // if (this.searchParam.shipId != shipId || this.searchParam.installationPoint != installationPoint) {
      //   this.searchParam.shipId = shipId;
      //   this.searchParam.installationPoint = installationPoint
      //   // this.queryVideoList();
      // }
      if (data.type == 'camera') {
        if (this.videoList[this.selectVideoIndex]) {
          //this.videoList[this.selectVideoIndex] = data
          const videoData = { ...data }
          videoData.code = videoData.id
          this.$set(this.videoList, this.selectVideoIndex, videoData)
        }
      }
    },
    playVideo(video, isRealTime) {
      const videoInfo = { ...video }
      if (isRealTime) {
        videoInfo.timeRange = undefined
      } else {
        if (!videoInfo.timeRange || videoInfo.timeRange.length != 2) {
          this.$message.warning('请选择时间范围！')
          return
        }
      }
      this.$refs.videoDialog?.open(videoInfo)
    },
    // 获取缩略图样式
    getShotcutImgStyle(imgUrl) {
      const picUrl = `${process.env.VUE_APP_MINIO}${this.$setting.downloadUrl}?objectName=` + encodeURIComponent(imgUrl)
      return `background-image:url('${picUrl}')`
    },
    timeRangeChanged(video, timeInfo) {
      if (timeInfo && timeInfo.length == 2) {
        const now = new Date()
        const startTime = new Date(timeInfo[0])
        const timeEnd = new Date(timeInfo[1])
        if (timeEnd.getTime() > now.getTime()) {
          this.$message.warning('历史时间范围不能包含未来时间')
          video.timeRange = undefined
          return
        }
        if (timeEnd.getTime() - startTime.getTime() < 10000) {
          this.$message.warning('历史时间范围不能小于10秒')
          video.timeRange = undefined
        }
      }
    },
    changePanel(size) {
      this.panelSize = size
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 18px;
}
::v-deep .el-range-editor.el-input__inner {
  padding: 3px 5px;
}
.app-view {
  // margin:0 !important;
}
.page-card {
  height: calc(100% - 40px) !important;
}
.video-tree-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-start;
  .ship-tree-panel {
    width: 220px;
    height: 100%;
    padding: 0px 20px 10px 10px;
    border-right: 2px solid #e1e1e1;
    flex-shrink: 0;

    .company-selector {
      margin-bottom: 10px;
    }
  }

  .video-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding-left: 5px;
    padding-top: 0px !important;
    &.big {
      position: fixed;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      z-index: 9999;
      background: #fff;
      padding: 0;
    }
    .tools {
      display: flex;

      justify-content: flex-start;
      align-items: center;
      .right-box {
        flex: 1;
        text-align: right;
        span {
          cursor: pointer;
        }
      }
      .btn {
        font-size: 26px;
        cursor: pointer;
        margin-right: 5px;
        color: gray;
      }
      .selected {
        color: rgb(15, 176, 230);
      }
    }
    .video-list {
      // width:1270px;
      // height:714px;
      flex: 1;
      display: grid;
      grid-row-gap: 5px;
      grid-column-gap: 5px;

      .video-item {
        background-color: #787878;
        border: 2px solid #787878;
        overflow: hidden;

        display: flex;
        align-items: center;
        justify-content: center;
      }
      .selected {
        border: 2px solid red;
      }
    }
    .video-list-grid1 {
      grid-template-columns: 100%;
      grid-template-rows: 100%;
      // grid-template-columns: 1250px;
      // grid-template-rows: 703px;
    }

    .video-list-grid4 {
      grid-template-columns: 50% 50%;
      grid-template-rows: 50% 50%;
      // grid-template-columns: 625px  625px;
      // grid-template-rows: 352px 352px;
    }

    .video-list-grid9 {
      grid-template-columns: 33.3% 33.3% 33.3%;
      grid-template-rows: 33.3% 33.3% 33.3%;
      // grid-template-columns: 420px 420px 420px;
      // grid-template-rows: 236px 236px 236px;
    }
  }
}
.treeIcon {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
}
.warn-page {
  min-height: 100% !important;
  ::v-deep .pagecard {
    min-height: calc(100vh - 3.8vw - 40px);
    .content {
      min-height: calc(100vh - 3.8vw - 40px - 48px - 40px);
      .video-tree-container {
        min-height: calc(100vh - 3.8vw - 40px - 48px - 40px - 30px);
        .ship-tree-panel {
          min-height: 100%;
          height: auto;
        }
      }
    }
  }
  .video-container {
    height: auto;
    padding-right: 40px;
    padding-bottom: 20px;
  }
}
</style>
